package com.tyc.wx.utills;

import com.alibaba.fastjson.JSONObject;
import com.tyc.wx.model.WxProperties;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @Description: java类作用描述
 * @Author: tyc
 * @CreateDate: 2020/12/29 15:56
 */
public class PublicUtill {

    private WxProperties wxProperties;

    public PublicUtill(WxProperties wxProperties) {
        this.wxProperties = wxProperties;
    }

    /**
     *验证消息是否来自微信服务器
     * 验证成功后 用户关注 取消关注等信息都会向配置的服务器地址发送post请求
     * @return
     */
    public boolean authenticate(String signature,String timestamp,String nonce){
        String[] str = new String[]{timestamp,nonce,wxProperties.getToken()};
        //排序
        Arrays.sort(str);
        //拼接字符串
        StringBuffer buffer = new StringBuffer();
        for(int i =0 ;i<str.length;i++){
            buffer.append(str[i]);
        }
        //进行sha1加密
        String temp = SHA1.encode(buffer.toString());
        //与微信提供的signature进行匹对
        return signature.equals(temp);
    }

    /**
     * 将微信服务器发过来的XML数据转换成Map
     * @param request
     * @return
     */
    public Map<String, String> xmlToMap(HttpServletRequest request){
        Map<String, String> map = new HashMap<String, String>();
        SAXReader reader = new SAXReader();
        InputStream in = null;
        try {
            in = request.getInputStream();
            Document doc = reader.read(in);
            Element root = doc.getRootElement();
            List<Element> list = root.elements();
            for (Element element : list) {
                map.put(element.getName(), element.getText());
            }
        } catch (IOException e) {
        } catch (DocumentException e) {
        } finally {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
        return map;
    }

    public String getAccessToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token" + "?grant_type=client_credential&appid=" + wxProperties.getPublic_appid()
                + "&secret=" + wxProperties.getPublic_secret();
        String result = HttpClientUtil.doGet(url,null);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getString("access_token");
    }


    /**
     * h5静默授权
     * @param code
     * @return
     */
    public String getOpenidByCode(String code){
        Map params = new HashMap();
        params.put("secret", wxProperties.getPublic_appid());
        params.put("appid", wxProperties.getMini_secret());
        params.put("grant_type", "authorization_code");
        params.put("code", code);
        String openid = null;
        try {
            String result = HttpClientUtil.doGet(
                    "https://api.weixin.qq.com/sns/oauth2/access_token",params);
            JSONObject jsonObject = JSONObject.parseObject(result);
            openid = jsonObject.get("openid").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return openid;
    }


    public boolean sendTemplateMessage(String access_token,String message){
        boolean flag = false;
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;
        String result1 = HttpClientUtil.doPostJson(url,JSONObject.toJSONString(message));
        JSONObject wxResult = JSONObject.parseObject(result1);
        if(wxResult.get("errcode").toString().equals("0")){
            flag = true;
        }
        return flag;
    }
}
